package cn.highedu.coolsharkhub;

/**
 * 线程安全的银行账户
 * 设计一个线程安全的银行账号类BankAccount 提供三个方法
 * 存钱deposit 存钱，存的金额是负的，返回相应的错误
 * 取钱withdraw 从账户中取钱，取钱金额为负或大于账户余额，返回相应错误
 * 查看账户余额get 返回当前账户的余额
 */
public class Demo08 {

    public static void main(String[] args) {
        //创建银行账户
        BankAccount account=new BankAccount(1000);
        Thread depositThread=new Thread(()->{
            for (int i=0;i<5;i++){
                account.deposit(100);
            }
        });
        Thread withdrawThread=new Thread(()->{
            for (int i=0;i<5;i++){
                account.withdraw(300);
            }
        });

        depositThread.start();
        withdrawThread.start();
/*        try {
            depositThread.join();
            withdrawThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        System.err.println("当前账户："+account.get()+"元");
    }
}
class BankAccount{
    private double money;

    public BankAccount(int money) {
        this.money = money;
    }
    //存钱方法
    public synchronized void deposit(int money){
        if (money > 0) {
            this.money+=money;
            System.out.println("存钱成功"+money+"元");
            System.out.println(this.money);
        }else {
            System.out.println("存钱金额有误，存钱失败");
        }
    }
    //取钱方法
    public synchronized void withdraw(int money){
        if (this.money>=money&&money>0){
            this.money-=money;
            System.out.println("取钱成功："+money+"元");
            System.out.println(this.money);
        }else {
            System.out.println("取钱金额有误，取钱失败");
        }
    }
    public double get(){
        return money;
    }

}
